package www.ld.com.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import www.ld.com.domain.R;
import www.ld.com.exception.BaseException;
import www.ld.com.exception.ValidateException;

@RestControllerAdvice(basePackages = "www.ld.com.controller")
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        log.info("异常：{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        return R.error(bindingResult.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(BindException.class)
    public R handleException(BindException e) {
        return R.error(e.getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R handleException(HttpMessageNotReadableException e) {
        log.error("异常：{}", e.getMessage());
        return R.error("参数转换异常");
    }


    @ExceptionHandler(ValidateException.class)
    public R handleException(ValidateException e) {
        log.error("异常：{}", e.getMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler(ConversionFailedException.class)
    public R handleException(ConversionFailedException e) {
        log.error("异常：{}", e.getMessage());
        return R.error("参数传参异常");
    }

    @ExceptionHandler(AccessDeniedException.class)
    public R handleException(AccessDeniedException e) {
        log.error("异常：{}", e.getMessage());
        return R.error(e.getMessage());
    }


    @ExceptionHandler(BaseException.class)
    public R handleException(BaseException e) {
        log.error("异常：{}", e.getMessage());
        return R.error(e.getMessage());
    }
    @ExceptionHandler(BadCredentialsException.class)
    public R handleException(BadCredentialsException e){
        log.error("异常：{}", e);
        return R.error("未知错误：请查看日志"+e);
    }
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable e) {
        log.error("异常：{}", e);
        return R.error("未知错误：请查看日志");
    }


}
